########################################################################
#  Pyfm - personal finance data-base
#  Copyright (C) 2007,8 Ehud Ben-Reuven
#  udi@benreuven.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
########################################################################
from lib.quoteinterface import getFXrate

class GainLoss(dict):
    """Build a table of gain and loss
for each category. Categories may have hierachical structure.
The category is broken into hireachies using the '.' seperator.
"""
    def __init__(self,curdef=None):
        self.curdef=curdef
    def inc(self,category,cost):
        if not cost: return
        self.setdefault(category,[0,0])
        if cost>0:
            self[category][0]+=cost
        else:
            self[category][1]+=cost
    def inc2(self,category,gainloss):
        self.inc(category,gainloss[0])
        self.inc(category,gainloss[1])
    def add(self,category,cost,dt=None,currency=None):
        if not cost: return
        if dt and currency and self.curdef:
            cost*=getFXrate(dt,currency,self.curdef)
        self.inc(category,cost)
    def strval(self,t):
        v=self[t]
        s=''
        if v[0] and v[1]:
            s+="%.2f="%(v[0]+v[1])
        if v[0]:
            s+="%.2f"%v[0]
        if v[1]:
            s+="%.2f"%v[1]
        return s       
    def strpair(self,t):
        return t+':'+self.strval(t)
    def __str__(self,sep=' '):
        keys=self.keys()
        keys.sort()
        s=[self.strpair(t) for t in keys if not t.startswith('_')]
        return sep.join(s)
    def pprint(self):
        print
        if not self: return
        d=GainLoss()
        for key in self:
            if key.startswith('_'): continue
            d.inc2('_TOTAL_',self[key])            
            t=key
            while t:
                d.inc2(t,self[key])
                t,s,r=t.rpartition('.')
        print d.__str__('\n')
        if len(self)>1:
            print d.strval('_TOTAL_')
    def join(self,other):
        assert self.curdef==other.curdef
        for t in other:
            self.inc2(t,other[t])
